﻿using System;
using System.Linq;
using System.Windows.Data;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Collections;
using System.ServiceModel.DomainServices.Client;
using System.Reflection;
using System.Collections.ObjectModel;

namespace SL.MVVMS.RIA
{
    public class RIACollectionViewGroup : CollectionViewGroup, INotifyPropertyChanged
    {
        RIACollectionViewGroup parentGroup;

        bool isBottom;
        public override bool IsBottomLevel
        {
            get { return isBottom; }
        }

        public int Level
        {
            get
            {
                if (parentGroup == null)
                    return 0;
                else
                    return parentGroup.Level + 1;
            }
        }

        public RIACollectionViewGroup(RIACollectionViewGroup parent, Object groupName)
            : base(groupName)
        {
            isBottom = true;
            if (parent != null)
                parent.isBottom = false;
            this.parentGroup = parent;
        }
        
        internal void IndexOf(Object item)
        {
            ProtectedItems.IndexOf(item);
        }
        internal void Add(Object item)
        {
            ProtectedItems.Add(item);
            if (item is CollectionViewGroup)
                IncrementCount(((RIACollectionViewGroup)item).ItemCount);
            else
                IncrementCount();
        }
        internal void AddAt(int index, Object item)
        {
            ProtectedItems.Insert(index, item);
            if (item is CollectionViewGroup)
                IncrementCount(((RIACollectionViewGroup)item).ItemCount);
            else
                IncrementCount();
        }
       internal void Remove(Object item)
        {
            ProtectedItems.Remove(item);
            if (item is CollectionViewGroup)
                DecrementCount(((RIACollectionViewGroup)item).ItemCount);
            else
                DecrementCount();
        }

       private void IncrementCount(int amount = 1)
       {
           if (amount == 0)
               return;

           ProtectedItemCount += amount;
           if (parentGroup != null)
               parentGroup.IncrementCount();
       }
       private void DecrementCount(int amount = 1)
        {
            if (amount == 0)
                return;

            ProtectedItemCount -= amount;
            if (parentGroup != null)
                parentGroup.DecrementCount();
        }

    }
}
